# -*- coding: utf-8 -*-
import sys  
reload(sys)
sys.setdefaultencoding('utf8')  
import string
import cgi
import urllib
import random
import datetime
from google.appengine.ext import db
from google.appengine.api.labs import taskqueue
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class ReapJob(db.Model):
	jobobj = db.StringProperty(required=True)
	reapurl = db.StringProperty(required=True)
	createdtime = db.DateTimeProperty(required=True, auto_now_add=True)

class ReapHandler(webapp.RequestHandler):
	def get(self):
		if cgi.escape(self.request.get('guard')) != "":
			urlcron = "/reapall?email=flamepjlh@126.com&pwd=flamehjhj"
			taskregql = ReapJob.gql("WHERE jobobj = :1", "flamepjlh@126.com")
			taskrecord = taskregql.get()
			countdowntime = 0
			if taskrecord == None:
				countdowntime = 5
				taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='126restore'+str(random.randint(1,999999)))
			else:
				datetimenow = datetime.datetime.now()
				if taskrecord.createdtime < datetimenow:
					taskrecord.delete()
					countdowntime = 5
					taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='126restore'+str(random.randint(1,999999)))
			urlcron = "/reapall?email=flamepjlh@163.com&pwd=flamehjhj"
			taskregql = ReapJob.gql("WHERE jobobj = :1", "flamepjlh@163.com")
			taskrecord = taskregql.get()
			if countdowntime != 0:
				countdowntime += countdowntime + 95 + random.randint(1,60)
			if taskrecord == None:
				taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='163restore'+str(random.randint(1,999999)))
			else:
				datetimenow = datetime.datetime.now()
				if taskrecord.createdtime < datetimenow:
					taskrecord.delete()
					taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='163restore'+str(random.randint(1,999999)))
			urlcron = "/reapall?email=fxckgfw1@gmail.com&pwd=flamehjhj"
			taskregql = ReapJob.gql("WHERE jobobj = :1", "fxckgfw1@gmail.com")
			taskrecord = taskregql.get()
			if countdowntime != 0:
				countdowntime += countdowntime + 95 + random.randint(1,60)
			if taskrecord == None:
				taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='gmailrestore'+str(random.randint(1,999999)))
			else:
				datetimenow = datetime.datetime.now()
				if taskrecord.createdtime < datetimenow:
					taskrecord.delete()
					taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='gmailrestore'+str(random.randint(1,999999)))
			return
		if cgi.escape(self.request.get('retry')) != "":
			retry = string.atoi(cgi.escape(self.request.get('retry')))
		else:
			retry = 0
		if cgi.escape(self.request.get('feed')) == "true":
			urlfeed = 'http://twmsg.tk/wp-reap/feed.php?'
		else:
			urlreap = 'http://twmsg.tk/wp-reap/reap.php?'
		if cgi.escape(self.request.get('email')) != "":
			useremail = cgi.escape(self.request.get('email'))
		else:
			useremail = 'flamepjlh@126.com'
			userpasswords = 'flamehjhj'
			helper = '246059230'
		if cgi.escape(self.request.get('pwd')) != "":
			userpasswords = cgi.escape(self.request.get('pwd'))
		if cgi.escape(self.request.get('setcron')) == "true":
			if cgi.escape(self.request.get('time')) != "":
				if cgi.escape(self.request.get('time')) != "99999999":
					countdowntime = string.atoi(cgi.escape(self.request.get('time')))*60
				else:
					return
				self.response.out.write('countdowntime:' + str(countdowntime))
				urlcron = "/reapall?cron=true" + '&email=' + useremail + '&pwd=' + userpasswords
				self.response.out.write(urlcron)
				timetoexecute = datetime.datetime.now()
				timetoexecute = timetoexecute + datetime.timedelta(seconds=countdowntime)
				taskregql = ReapJob.gql("WHERE jobobj = :1", useremail)
				taskrecord = taskregql.get()
				if taskrecord == None:
					taskqueue.add(url=urlcron, payload=None, eta=timetoexecute, method='GET', name='next'+cgi.escape(self.request.get('time'))+'r'+str(random.randint(1,999999)));
					nextjob = ReapJob(jobobj=useremail, reapurl=urlcron, createdtime=timetoexecute)
					nextjob.put()
					self.response.out.write('success add!'+useremail)
				else:
					self.response.out.write('job already exist!:'+useremail)
			else:
				urlcron = 'http://twmsg.tk/wp-reap/getreaptime.php?' + 'email=' + useremail + '&pwd=' + userpasswords
				try:
					result = urlfetch.fetch(url=urlcron, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; zh-CN) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'},follow_redirects = True, allow_truncated=True, deadline=30)
				except:
					urlcron = "/reapall?setcron=true" + '&email=' + useremail + '&pwd=' + userpasswords
#					taskqueue.add(url=urlcron, payload=None, method='GET', countdown=5, name='setnextcron')
			return
		if cgi.escape(self.request.get('helper')) != "":
			helper = cgi.escape(self.request.get('helper'))
		else:
			helper = ""
		if cgi.escape(self.request.get('feed')) == "true":
			if helper == "":
				urlfeed = urlfeed + 'email=' + useremail + '&pwd=' + userpasswords
			else:
				urlfeed = urlfeed + 'email=' + useremail + '&pwd=' + userpasswords + '&helper=' + helper
			try:
				result = urlfetch.fetch(url=urlfeed, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; zh-CN) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'},follow_redirects = True, allow_truncated=True, deadline=30)
			except:
				if helper == "":
					urlcron = "/reapall?feed=true" + '&email=' + useremail + '&pwd=' + userpasswords + '&retry=' + str(retry + 1)
				else:
					urlcron = "/reapall?feed=true" + '&email=' + useremail + '&pwd=' + userpasswords + '&helper=' + helper + '&retry=' + str(retry + 1)
				if retry < 5:
					taskqueue.add(url=urlcron, payload=None, method='GET', countdown=15, name='retryfeed'+str(random.randint(1,999999)))
				return
			self.response.out.write('success feed!'+useremail+helper)
		else:
			urlreap = urlreap + 'email=' + useremail + '&pwd=' + userpasswords
			if cgi.escape(self.request.get('cron')) != "":
				taskregql = ReapJob.gql("WHERE jobobj = :1", useremail)
				taskrecord = taskregql.get()
				if taskrecord != None:
					taskrecord.delete()
			try:
				result = urlfetch.fetch(url=urlreap, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; zh-CN) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'},follow_redirects = True, allow_truncated=True, deadline=30)
			except:
				urlcron = "/reapall?" + 'email=' + useremail + '&pwd=' + userpasswords + '&retry=' + str(retry + 1)
				if retry < 10:
					taskqueue.add(url=urlcron, payload=None, method='GET', countdown=15, name='retryreap'+str(random.randint(1,999999)))
					return
			urlcron = "/reapall?setcron=true" + '&email=' + useremail + '&pwd=' + userpasswords
			taskqueue.add(url=urlcron, payload=None, method='GET', countdown=10, name='setnextcron'+str(random.randint(1,999999)))
			self.response.out.write('success reap!'+useremail)


application = webapp.WSGIApplication(
																		 [('/reapall', ReapHandler)],
																		 debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()